package com.zyx.concurrentdemo.mytest.c08;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author Yaxi.Zhang
 * @since 2021/10/19 14:22
 */
@Slf4j(topic = "c.ThreadExeceptionHandler")
public class ThreadExeceptionHandler {
    public static void main(String[] args) {
        method2();
    }

    /**
     * 处理线程池中异常的方式1: 直接接受抛出的异常
     */
    public static void method1() {
        ExecutorService pool = Executors.newFixedThreadPool(1);
        pool.submit(() -> {
            try {
                log.debug("task1");
                int i = 1 / 0;
            } catch (Exception e) {
                log.error("error:", e);
            }
        });
    }

    /**
     * 处理线程池中异常的方式1: 直接接受抛出的异常
     */
    public static void method2() {
        ExecutorService pool = Executors.newFixedThreadPool(1);
        for (int i = 0; i < 3; i++) {
            Future<Boolean> f = pool.submit(() -> {
                log.debug("task1");
                Thread.sleep(3000);
                int j = 1 / 0;
                return true;
            });
            try {
                log.debug("result:{}", f.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
